package com.hghivln.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hghivln.constants.Constants;
import com.hghivln.mapper.DictDataMapper;
import com.hghivln.mapper.DictTypeMapper;
import com.hghivln.pojo.domain.DictData;
import com.hghivln.pojo.domain.DictType;
import com.hghivln.pojo.dto.DictTypeDto;
import com.hghivln.pojo.vo.AjaxResult;
import com.hghivln.service.DictTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class DictTypeServiceImpl implements DictTypeService {

    @Autowired
    private DictTypeMapper dictTypeMapper;

    @Autowired
    private DictDataMapper dictDataMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public AjaxResult listPage(DictTypeDto dictTypeDto) {
        Page<DictType> page = new Page<>(dictTypeDto.getPageNum(), dictTypeDto.getPageSize());
        QueryWrapper<DictType> qw = new QueryWrapper<>();
        qw.like(StringUtils.isNotBlank(dictTypeDto.getDictName()), DictType.COL_DICT_NAME, dictTypeDto.getDictName());
        qw.like(StringUtils.isNotBlank(dictTypeDto.getDictType()), DictType.COL_DICT_TYPE, dictTypeDto.getDictType());
        qw.eq(StringUtils.isNotBlank(dictTypeDto.getStatus()), DictType.COL_STATUS, dictTypeDto.getStatus());
        qw.ge(dictTypeDto.getBeginTime() != null, DictType.COL_CREATE_TIME, dictTypeDto.getBeginTime());
        qw.le(dictTypeDto.getEndTime() != null, DictType.COL_CREATE_TIME, dictTypeDto.getEndTime());
        dictTypeMapper.selectPage(page, qw);
        return AjaxResult.success("查询成功", page.getRecords(), page.getTotal());
    }

    @Override
    public int insert(DictTypeDto dictTypeDto) {
        DictType dictType = new DictType();
        BeanUtil.copyProperties(dictTypeDto, dictType);
        dictType.setCreateTime(DateUtil.date());
        dictType.setCreateBy(dictTypeDto.getSimpleUser().getUserName());
        return dictTypeMapper.insert(dictType);
    }

    @Override
    public int update(DictTypeDto dictTypeDto) {
        DictType dictType = new DictType();
        BeanUtil.copyProperties(dictTypeDto, dictType);
        dictType.setUpdateBy(dictTypeDto.getSimpleUser().getUserName());
        return dictTypeMapper.updateById(dictType);
    }

    @Override
    public int deleteDitypeByIds(Long[] dictIds) {
        List<Long> ids = Arrays.asList(dictIds);
        if (ids.size() > 0) {
            return dictTypeMapper.deleteBatchIds(ids);
        } else {
            return -1;
        }
    }

    @Override
    public AjaxResult list() {
        QueryWrapper<DictType> qw = new QueryWrapper<>();
        qw.eq(DictType.COL_STATUS, Constants.STATUS_TRUE);
        return AjaxResult.success(dictTypeMapper.selectList(qw));
    }

    @Override
    public DictType selectDictTypeById(Long dictId) {
        return dictTypeMapper.selectById(dictId);
    }

    @Override
    public Boolean checkDictTypeUnique(Long dictId, String dictType) {
        dictId = (dictId == null) ? -1L : dictId;
        QueryWrapper<DictType> qw = new QueryWrapper<>();
        qw.eq(DictType.COL_DICT_TYPE, dictType);
        DictType type = dictTypeMapper.selectOne(qw);
        // true :说明该字典类型 存在, false：不存在 。
        // 当type存在，ip不相同，说明数据库存在字典类型，不可以修改。当type存在，ip又相同，说明可以修改当前字典类型。
        if (type != null && dictId.longValue() != type.getDictId().longValue()) {
            return true;
        }
        return false;
    }

    /**
     * 同步缓存
     * 1、查询出所有可用的字典类型数据
     * 2、根据字典类型数据查找字典数据
     * 3、把字典数据生成json存到redis中
     * 例： dict:sys_user_sex --->[{},{},{}]
     */
    @Override
    public void dictCacheAsync() {
        QueryWrapper<DictType> qw = new QueryWrapper<>();
        qw.eq(DictType.COL_STATUS,Constants.STATUS_TRUE);
        List<DictType> dictTypeList = dictTypeMapper.selectList(qw);
        dictTypeList.forEach(dictType -> {
            QueryWrapper<DictData> qwd = new QueryWrapper<>();
            qwd.eq(DictData.COL_STATUS,Constants.STATUS_TRUE);
            qwd.eq(DictData.COL_DICT_TYPE,dictType.getDictType());
            qwd.orderByAsc(DictData.COL_DICT_SORT);
            List<DictData> dictDataList = dictDataMapper.selectList(qwd);
            // 转成 json
            String json = JSON.toJSONString(dictDataList);
            ValueOperations<String, String> opsForValuse = redisTemplate.opsForValue();
            opsForValuse.set(Constants.DICT_REDIS_PROFIX+dictType.getDictType(),json);
        });
    }

}
